<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2011 Grzegorz Bańka <grzegorz@grzegorzbanka.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */


$LANG->includeLLFile('EXT:mt_webmenager/mod1/locallang.xml');
require_once(PATH_t3lib . 'class.t3lib_scbase.php');
require_once(PATH_t3lib.'class.t3lib_tsparser.php');
require_once (PATH_t3lib.'class.t3lib_pagetree.php');

$BE_USER->modAccess($MCONF,1);	// This checks permissions and exits if the users has no permission for entry.
	// DEFAULT initialization of a module [END]

define('DS', DIRECTORY_SEPARATOR); // I always use this short form in my code.

/**
 * Module 'MT Menager' for the 'mt_webmenager' extension.
 *
 * @author	Grzegorz Bańka <grzegorz@grzegorzbanka.com>
 * @package	TYPO3
 * @subpackage	tx_mtwebmenager
 */
class  tx_mtwebmenager_module1 extends t3lib_SCbase {
				var $pageinfo;

				/**
				 * Initializes the Module
				 * @return	void
				 */
				function init()	{
					global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;

					parent::init();

					/*
					if (t3lib_div::_GP('clear_all_cache'))	{
						$this->include_once[] = PATH_t3lib.'class.t3lib_tcemain.php';
					}
					*/
				}

				/**
				 * Adds items to the ->MOD_MENU array. Used for the function menu selector.
				 *
				 * @return	void
				 */
				function menuConfig()	{
					global $LANG;
					$this->MOD_MENU = Array (
						'function' => Array (
							'1' => $LANG->getLL('function1'),
							'2' => $LANG->getLL('function2'),
							'3' => $LANG->getLL('function3')
						)
					);
					parent::menuConfig();
				}

				/**
				 * Main function of the module. Write the content to $this->content
				 * If you chose "web" as main module, you will need to consider the $this->id parameter which will contain the uid-number of the page clicked in the page tree
				 *
				 * @return	[type]		...
				 */
				function main()	{
					global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;

					// Access check!
					// The page will show only if there is a valid page and if this page may be viewed by the user
					$this->pageinfo = t3lib_BEfunc::readPageAccess($this->id,$this->perms_clause);
					$access = is_array($this->pageinfo) ? 1 : 0;

					if (($this->id && $access) || ($BE_USER->user['admin'] && !$this->id))	{

							// Draw the header.
						$this->doc = t3lib_div::makeInstance('mediumDoc');
$this->doc->inDocStyles .= '
.installweb {
padding:10px;
}
.clear {
clear:both;
}
.installweb label {
width:250px;
 text-align:right;
 padding-right:10px;
display:block;
float:left;
padding-top:3px;
}
.mtpage_uid, .mtsettings {
padding:5px;
}
div.typo3-mediumDoc {
width:100%;
}
.mt_error {
padding:3px;
color:#fff;
background:red;
}
.mtrow {
border:0 solid #666666;
border-bottom-width:1px;
margin-bottom:5px;
padding-bottom:5px;
}
#mt_process_1 {
display:none;
}
.installweb li {
padding-bottom:10px;
}
#mt_export_par1,#mt_export_finish,#mt_import_finish {
display:none;
}
#mt_export_finish_load {
}
#treemtinstall {
padding:4px;
}
#treemtinstall td {
padding:5px 10px;
border:0px solid #000000;
border-bottom-width:1px;
margin-bottom:3px;
border-left-width:1px;
}
.mt_option {
margin:5px;
border:1px solid;
padding:5px;
}
						';
						
						$this->doc->backPath = $BACK_PATH;
						$this->doc->form='<form action="" method="post" enctype="multipart/form-data">';

							// JavaScript
						$this->doc->JScode = '
							<script language="javascript" type="text/javascript">							
								script_ended = 0;
								function jumpToUrl(URL)	{
									document.location = URL;
								}
							</script>
						';
						$this->doc->postCode='
							<script language="javascript" type="text/javascript">
								script_ended = 1;
								if (top.fsMod) top.fsMod.recentIds["web"] = 0;
							</script>
						';

						$headerSection = $this->doc->getHeader('pages', $this->pageinfo, $this->pageinfo['_thePath']) . '<br />'
							. $LANG->sL('LLL:EXT:lang/locallang_core.xml:labels.path') . ': ' . t3lib_div::fixed_lgd_cs($this->pageinfo['_thePath'], -50);

						$this->content.=$this->doc->startPage($LANG->getLL('title'));
						$this->content.=$this->doc->header($LANG->getLL('title'));
						$this->content.=$this->doc->spacer(5);
						$this->content.=$this->doc->section('',$this->doc->funcMenu($headerSection,t3lib_BEfunc::getFuncMenu($this->id,'SET[function]',$this->MOD_SETTINGS['function'],$this->MOD_MENU['function'])));
						$this->content.=$this->doc->divider(5);


						// Render content:
						$this->moduleContent();


						// ShortCut
						if ($BE_USER->mayMakeShortcut())	{
							$this->content.=$this->doc->spacer(20).$this->doc->section('',$this->doc->makeShortcutIcon('id',implode(',',array_keys($this->MOD_MENU)),$this->MCONF['name']));
						}

						$this->content.=$this->doc->spacer(10);
					} else {
							// If no access or if ID == zero

						$this->doc = t3lib_div::makeInstance('mediumDoc');
						$this->doc->backPath = $BACK_PATH;

						$this->content.=$this->doc->startPage($LANG->getLL('title'));
						$this->content.=$this->doc->header($LANG->getLL('title'));
						$this->content.=$this->doc->spacer(5);
						$this->content.=$this->doc->spacer(10);
					}
				
				}

				/**
				 * Prints out the module HTML
				 *
				 * @return	void
				 */
				function printContent()	{

					$this->content.=$this->doc->endPage();
					echo $this->content;
				}

				/**
				 * Generates the module content
				 *
				 * @return	void
				 */
				function moduleContent()	{
					switch((string)$this->MOD_SETTINGS['function'])	{
						case 1:
							if(!isset($_POST['mt_finish_all']))
							{
								if(!isset($_POST['installmtweb'])) $content=$this->get_mtwebmenager();
								else if(!isset($_POST['installweb_all'])) $content=$this->get_webtree();
								else
								{
									$get_error=$this->check_install_set();
									if($get_error==0)
									{
										$content=$this->mtweb_install();
									}else 
									{
										$content=$this->show_error($get_error);
										$content.=$this->get_webtree();
									}
								}
							}else {
								$content=$this->finish_import();
							}
							
							$content='<div class="installweb">'.$content.'</div>';
							$this->content.=$this->doc->section('Install your new template/view:',$content,0,1);
						break;
						case 2:
							if(!isset($_POST['mt_finish_all']))
							{
								$content='<div align=center><strong>Export your template/view:</strong></div>';
								if(!isset($_GET['id']) && !isset($_POST['mt_page_uid']))
								{
									$content=$this->get_export_form();
								}if(!isset($_POST['mt_export']) && !isset($_POST['mt_export_pack'])) {
									$page_uid=$_GET['id']?$_GET['id']:$_POST['mt_page_uid'];
									$content=$this->get_export_form(intval($page_uid));
								}elseif(!isset($_POST['mt_export_pack'])) $content=$this->get_export_part();
								else 
								{
									$name=$_POST['mt_export_name'];
									$path=$_SERVER['DOCUMENT_ROOT'];
									if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
									$path_mtwebmenager=$path.'fileadmin/mtwebmenager/';									
									if(is_file($path_mtwebmenager.$name.'.zip') && !isset($_POST['mt_overwrite_template']))
									{
										$content.= '<h1 class="mt_error">szablon o nazwie '.$name.' już istnieje, możesz nadpisać istniejący szablon.</h1>';
										$content.=$this->get_export_part();
									}
									else $content=$this->get_export_start();
								}
							}else
							{
								$content=$this->finish_export();
								// finish export
								//print_r($_POST);
								//print_r($_SERVER);
							}
							$this->content.=$this->doc->section('Export to MT System template/view:',$content,0,1);
						break;
						case '3':
							if(!isset($_POST['repair'])) $content=$this->repair_process();
							else $content=$this->repair_porocess_progress($_POST['repair']);
							$this->content.=$this->doc->section('Repair export process:',$content,0,1);
						break;
					}
				} 
			function repair_porocess_progress($file)
			{
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
				$mtcache=$path.'fileadmin/mtwebmenager/mtcache';	
				
				$file=explode('- ',$file);
				$name=$file[count($file)-1];
				$file=$mtcache.'/'.$name;
				
				if(is_file($file))
				{
					$fopen=fopen($file,'r');
					$read=fread($fopen,filesize($file));
					$read=unserialize(base64_decode($read));
					$this->finish_export(1,$read);
					return 'Repair process is done - status OK!';
				}else return 'error file dont exists: '.$file;
			}
			function repair_process()
			{
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
				$mtcache=$path.'fileadmin/mtwebmenager/mtcache';
				
				$get=t3lib_div::getFilesInDir($mtcache,'mtcache');
				
				foreach($get as $file)
				{
					$add[]='
					<li>'.$file.' ('.date('d-m-Y H:i:s',filemtime($mtcache.'/'.$file)).') <input type="submit" value="Repair export - '.$file.'" name="repair" /></li>
					';
				}
				return '<ul>'.implode("\n",$add).'</ul>';
				
			}
			function get_all_constants($uid)
			{
				$where = 'deleted=0 AND hidden=0 AND pid='.$uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,constants','sys_template',$where,'','',1);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$constants=$row['constants'];
					$sys_uid=$row['uid'];
				}
				return array($sys_uid,$constants);
			}
			function finish_import()
			{
			
				global $LANG;
				/*
								<input name="mt_pack_name" type="hidden" value="'.$pack_name.'" />
								<input name="mt_page_path" type="hidden" value="'.$path.'" />
								<input name="mt_pack_pid" type="hidden" value="'.$pid.'" />
								
								<input name="mt_finish_all" type="submit" value="Finish import" />
				*/
				$name=addslashes($_POST['mt_pack_name']);
				$path=addslashes($_POST['mt_page_path']);
				$pid=intval($_POST['mt_pack_pid']);
				$www=addslashes($_POST['mt_pack_www']);

				
				$where = 'deleted=0 AND hidden=0 AND pid='.$pid.' AND title="'.$name.'ext"';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','pages',$where,'','');
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$page_uid=$row['uid'];	
				}
				if($page_uid!='')
				{
					
					$where = 'deleted=0 AND hidden=0 AND pid='.$page_uid.' AND is_siteroot=1';
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,storage_pid','pages',$where,'','');
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$root_uid=$row['uid'];	
						$storage_pid=$row['storage_pid'];
						$count_root++;
					}

					if($root_uid!='')
					{
						$where = 'deleted=0 AND pid='.$storage_pid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,t3_origuid,tx_mtwebmenager_mtorguid','tx_templavoila_datastructure',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							if($row['tx_mtwebmenager_mtorguid']=='' || $row['tx_mtwebmenager_mtorguid']==0) $row['tx_mtwebmenager_mtorguid']=$row['t3_origuid'];
							$org_tx_templavoila_datastructure[]=str_replace('@','',$row['tx_mtwebmenager_mtorguid']);
							$tx_templavoila_datastructure[str_replace('@','',$row['tx_mtwebmenager_mtorguid'])]=$row['uid'];
						}	
						$where = 'deleted=0 AND pid='.$storage_pid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,t3_origuid,tx_mtwebmenager_mtorguid','tx_templavoila_tmplobj',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							if($row['tx_mtwebmenager_mtorguid']=='' || $row['tx_mtwebmenager_mtorguid']==0) $row['tx_mtwebmenager_mtorguid']=$row['t3_origuid'];
							$org_tx_templavoila_tmplobj[]=str_replace('@','',$row['tx_mtwebmenager_mtorguid']);
							$tx_templavoila_tmplobj[str_replace('@','',$row['tx_mtwebmenager_mtorguid'])]=$row['uid'];
						}
					
						$where = 'deleted=0 AND pid='.$storage_pid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,description','tt_news_cat',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							if(stristr($row['description'],']}'))
							{
								list($tt_news_cat_org,$row['description'])=explode(']}',$row['description']);
								$tt_news_cat_org=str_replace('{[','',$tt_news_cat_org);
								$tt_news_cat_org_uid[$tt_news_cat_org]=$row['uid'];
								
								$update=array(
									'description'	=>	$row['description']
								);
								$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_news_cat','uid='.$row['uid'],$update);
								$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
							}
						}
						//print_r($tt_news_cat_org_uid);
					
						$where = 'hidden=0 AND pid='.$root_uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','sys_domain',$where,'','',1);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$domainNameUid=$row['uid'];
						}

						$this->update_domainName($www,$domainNameUid);
						
						$where = 'deleted=0 AND hidden=0 AND pid='.$root_uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,constants','sys_template',$where,'','',1);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$constans = $this->parseTS($row['constants']);
							//$config = $this->parseTS($row['config']);

							$alluid=$this->get_pagetree($page_uid);
							
							for($i=0; $i<count($alluid); $i++)
							{
							
								$newuid=$alluid[$i]['row']['uid'];
								$this->update_org_tv($newuid,$org_tx_templavoila_datastructure,$org_tx_templavoila_tmplobj,$tx_templavoila_datastructure,$tx_templavoila_tmplobj);
								$all_orguid[$this->get_orguid($newuid)]=$newuid;
								$this->update_content_orguid_import($newuid,'{$mtpathimport}',$path,$org_tx_templavoila_datastructure,$org_tx_templavoila_tmplobj,$tx_templavoila_datastructure,$tx_templavoila_tmplobj);
								
								list($old_fe_groups,$new_fe_groups)=$this->get_fe_groups($newuid);
								if($old_fe_groups!='') $get_fe_groups[$old_fe_groups]=$new_fe_groups;
								
								$all_page_pid[]=$newuid;
								
								$update=array(
									't3_origuid'	=>	'0'
								);
								$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$alluid[$i]['row']['uid'],$update);
								$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
								
							}
							
							for($i=2; $i<count($alluid); $i++)
							{
								$all_uid=$alluid[$i]['row']['uid'];
								list($sys_uid,$get_constants)=$this->get_all_constants($all_uid);
								
								list($all_config,$all_constans)=$this->import_ts($all_uid,'',$get_constants,$name,$www,$path,0);
								$all_constans=$this->parse_ts_tostring($all_constans,$get_constants,1,1,$all_orguid,$get_fe_groups,$tt_news_cat_org_uid);	

								$this->update_rootext($sys_uid,$all_constans,$all_config);	
							}

							
							list($config,$constans)=$this->import_ts($page_uid,$config,$constans,$name,$www,$path,1);
							$constans_mt=$constans;
							$constans=$this->parse_ts_tostring($constans,$row['constants'],1,1,$all_orguid,$get_fe_groups,$tt_news_cat_org_uid);
							//$config=$this->parse_ts_tostring($config);	
							
							$this->update_rootext($row['uid'],$constans,$config);			
							$this->update_domainName($www,$domainNameUid);					
							$this->tvobj_file_rename($storage_pid,'{$mtpathimport}',$path);
							
							$loc_path=$_SERVER['DOCUMENT_ROOT'];
							if($loc_path!='/') $loc_path=$loc_path.'/';
							
							$loc_file = $loc_path.'typo3conf/localconf.php';
							$loc_open = fopen($loc_file,"r");
							$loc_read=fread($loc_open,filesize($loc_file));
							fclose($loc_open);
							$loc_open = fopen($loc_file,"w");
							list($loc_read,$last_all)=explode('###DOMAIN_LIST###',$loc_read);
							//print_r($loc_read);
							$loc_add="						
	
	\$TYPO3_CONF_VARS['EXTCONF']['realurl']['".mysql_real_escape_string($www)."']=\$TYPO3_CONF_VARS['EXTCONF']['realurl']['_DEFAULT'];
	\$TYPO3_CONF_VARS['EXTCONF']['realurl']['".mysql_real_escape_string($www)."']['pagePath']['rootpage_id']=".$root_uid.";
							";
							$loc_start="";
							$loc_end="###DOMAIN_LIST###
							".$last_all;
							
							fwrite($loc_open,$loc_read.$loc_start.$loc_add.$loc_end);
							fclose($loc_open);
						
							t3lib_BEfunc::openPageTree(0);
							t3lib_BEfunc::setUpdateSignal('updatePageTree');
							$js="
							<script language=\"javascript\" type=\"text/javascript\">
									".t3lib_BEfunc::getUpdateSignalCode()."
							</script>
							";
							
							$setpath=$_SERVER['DOCUMENT_ROOT'];
							if($setpath!='/') $setpath=$setpath.'/';
							$setpath=$setpath.'fileadmin/templates/'.$path;
							if(is_dir($setpath))
							{
								$pack_file=$setpath.'/'.$name.'.t3d';
								unlink($pack_file);
							}
							
							//$allcontent_org=$all_orguid;
							
							//print_r($all_page_pid);
							$allcontent_org=$this->get_org_uidcontent($all_page_pid);		
							//
							//print_r('-------------');
							//print_r($allcontent_org);
							
							$no_domain=0;
							$where = 'deleted=0 AND hidden=0 AND is_siteroot=1';
							$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','pages',$where,'','');
							while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))		
							{
								$no_domain++;
							}			
							if(1==1)
							{
								$this->change_page_flex($all_page_pid,$allcontent_org,$all_orguid,$setpath);
								$this->change_ttcontent_flex($all_page_pid,$allcontent_org,$all_orguid,$setpath);
							}

							$update=array(
								't3_origuid'	=>	'0'
							);
							$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid!=0',$update);
							$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);							
							
							$where = 'deleted=0 AND pid='.$storage_pid;
							$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_templavoila_datastructure',$where);
							while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
							{
								$update=array(
									't3_origuid'	=>	'0',
									'tx_mtwebmenager_mtorguid'	=>	'0'
								);
								$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_templavoila_datastructure','uid='.$row['uid'],$update);
								$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
							}	
							$where = 'deleted=0 AND pid='.$storage_pid;
							$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_templavoila_tmplobj',$where);
							while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
							{
								$update=array(
									't3_origuid'	=>	'0',
									'tx_mtwebmenager_mtorguid'	=>	'0'
								);
								$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_templavoila_tmplobj','uid='.$row['uid'],$update);
								$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
							}
							$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid!=0',$update);
							$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
							$update=array(
								't3_origuid'	=>	'0',
								'tx_mtwebmenager_mtorguid'	=>	'0'
							);
							$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_content','uid!=0',$update);
							$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);		
							
							$constans=$constans_mt;
							if($constans['mtgenerate_websecode']!='' && $constans['mtgenerate_websecode']!='genmynew_code') $add_mtgenerate_websecode='<label>Security Code</label><input name="" type="text" value="'.$constans['mtgenerate_websecode'].'" /><br />';
							else $add_mtgenerate_websecode='';
							return $js.'
							<h2>'.$LANG->getLL('mt_import_finish').'</h2>
							<a href="http://'.$www.'" target="_blank">'.$LANG->getLL('mt_import_finish_show_www').'</a><br />
							<a href="/typo3/sysext/tstemplate/ts/index.php?&id='.$root_uid.'&SET[constant_editor_cat]=mt%20main%20settings&SET[function]=tx_tstemplateceditor" target="_blank">'.$LANG->getLL('mt_import_finish_show_settings').'</a><br />
							'.$add_mtgenerate_websecode;
						
						}						
						
					}else return  $this->show_error_view($LANG->getLL('text_import_error_rootuid'));
										
				}else return  $this->show_error_view($LANG->getLL('text_import_error_page_uid'));
				
			}
		
			function change_ttcontent_flex($alluid_page,$allcontent_org,$all_orguid,$setpath)
			{	
			
				$domainCount=0;
				$where = 'hidden=0';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','sys_domain',$where,'','',3);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$domainCount++;
				}
			
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
				
				$where = 'pid IN('.implode(',',$alluid_page).')';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('header,uid,tx_templavoila_flex,pid','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{			
					$page_pid=$row['pid'];
					$all_refindex=$this->ttcontentall_refindex($row['uid']);							
					$set_old_data=$rep_data=array();
					if($row['tx_templavoila_flex']!='')
					{
						preg_match_all('/<value index=\"vDEF\">(.*)<\/value>/',$row['tx_templavoila_flex'],$data);
						preg_match_all('/<field index=\"(.*)\">/',$row['tx_templavoila_flex'],$field);
					
						$data_array=$data[1];
						$field_array=$field[1];
																
						if($data_array!='')
						{
							for($i=0; $i<count($data_array); $i++)
							{
								$data_val=$data_array[$i];
								if($data_val[0]!='') 
								{

									
									if(stristr($data_val,','))
									{
										$data_exp=explode(',',$data_val);
									}else $data_exp=array($data_val);
											
									
																		
									if($data_exp[0]!='')
									{
										$rep_data=array();
										for($z=0; $z<count($data_exp); $z++)
										{
										
											if(stristr($field_array[$i],'field_content') || stristr($field_array[$i],'field_memcontent')) 
												
												if(in_array($data_exp[$z],$all_refindex) && $this->isinpage_pid($page_pid,$data_exp[$z],$alluid_page)==true)
												{
													//print_r($data_exp[$z].',');
												}
												else
												{
													if($allcontent_org[$data_exp[$z]]!='' && !in_array($data_exp[$z],$all_refindex)) $rep_data[]=$allcontent_org[$data_exp[$z]];
													else if($allcontent_org[$data_exp[$z]]!='')
													{
														
														if($this->isinpage_pid($page_pid,$allcontent_org[$data_exp[$z]],$alluid_page)==false && $domainCount!=1) $rep_data[]=$allcontent_org[$data_exp[$z]];
													}
												}
											
											
											if(stristr($field_array[$i],'field_link')) if($all_orguid[$data_exp[$z]]!='') $rep_data[]=$all_orguid[$data_exp[$z]]; 	
											
													
											if(stristr($field_array[$i],'field_image') && $data_exp[$z]!='')
											{

												if(!is_file($path.'uploads/tx_templavoila/'.$data_exp[$z])) 
												{
													$randtitle=md5(time()).rand(0,9);
													$randtitle=substr($randtitle,0,3);
													//print_r($path.'uploads/tx_templavoila/'.$randtitle.$data_exp[$z]);
													$this->copy_r($setpath.'/tvupload_files/'.$data_exp[$z],$path.'uploads/tx_templavoila/'.$randtitle.$data_exp[$z]);
													$rep_data[]=$randtitle.$data_exp[$z];
												}
												else
												{
													/*
													$randtitle=md5(time()).rand(0,9);
													$randtitle='cp'.substr($randtitle,0,3);
													
													$this->copy_r($setpath.'/tvupload_files/'.$data_exp[$z],$path.'uploads/tx_templavoila/'.$randtitle.$data_exp[$z]);
													$rep_data[]=$randtitle.$data_exp[$z];
													*/
													$rep_data[]=$data_exp[$z];
												}
											}	
																												
										}
										if(!stristr($field_array[$i],'field_text'))
										{
											$replace = '<value index="vDEF">'.implode(',',$rep_data).'</value>';
											$search = '<value index="vDEF">'.$data_val.'</value>';			
											
											//print_r($replace); print_r($search.'----------------'."\n");
																		
											if(implode(',',$rep_data)!='') $row['tx_templavoila_flex']=str_replace($search, $replace, $row['tx_templavoila_flex']);
										}else $is_string=1;											
									}
								}
							}
							$old_data=implode(',',$set_old_data);
						}
							
						$update=array(
							'tx_templavoila_flex'	=>	$row['tx_templavoila_flex']
						);

						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_content','uid='.$row['uid'],$update);
						$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);									
						
					}
				}
			
			}
//function change_ttcontent_flex($all_page_pid,$allcontent_org,$all_orguid,$setpath)
			function change_page_flex($alluid_page,$allcontent_org,$all_orguid,$setpath)
			{
				
				$domainCount=0;
				$where = 'hidden=0';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','sys_domain',$where,'','',3);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$domainCount++;
				}
				
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
			
				$is_string=0;
	
				//print_r($alluid_page);					
				$where = 'uid IN('.implode(',',$alluid_page).')';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('title,uid,tx_templavoila_flex ','pages',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{	
					$page_pid=$row['uid'];
					list($all_refindex,$flexpointer)=$this->pageall_refindex($row['uid']);					
					$set_old_data=$rep_data=array();
					if($row['tx_templavoila_flex']!='')
					{
						preg_match_all('/<value index=\"vDEF\">(.*)<\/value>/',$row['tx_templavoila_flex'],$data);
						preg_match_all('/<field index=\"(.*)\">/',$row['tx_templavoila_flex'],$field);
					
						$data_array=$data[1];
						$field_array=$field[1];
																
						if($data_array!='')
						{
						
							for($i=0; $i<count($data_array); $i++)
							{
								//$field_array=$allfield_array;
								$data_val=$data_array[$i];
								if($data_val[0]!='') 
								{
									

									
									if(stristr($data_val,','))
									{
										$data_exp=explode(',',$data_val);
									}else $data_exp=array($data_val);
																		
									if($data_exp[0]!='')
									{
										$rep_data=array();
										
										for($z=0; $z<count($data_exp); $z++)
										{
											if(stristr($field_array[$i],'field_content') || stristr($field_array[$i],'field_memcontent')) 
											{
												if(in_array($data_exp[$z],$all_refindex) && $this->isinpage_pid($page_pid,$data_exp[$z],$alluid_page)==true)
												{											
												}
												else
												{
													
													if($allcontent_org[$data_exp[$z]]!='' && !in_array($data_exp[$z],$all_refindex)) 
													{
															
														$rep_data[]=$allcontent_org[$data_exp[$z]];
														//1
													}
													else 
													{
														//print_r($flexpointer[$data_exp[$z]].'sDEF/lDEF/'.$field_array.'/vDEF/'."\n");
														if($flexpointer[$data_exp[$z]]=='sDEF/lDEF/'.$field_array[$i].'/vDEF/' && in_array($data_exp[$z],$all_refindex) && $this->isinpage_pid($page_pid,$data_exp[$z],$alluid_page)==false) 
														{
														}
														else
														{
															if($allcontent_org[$data_exp[$z]]!='')
															{
																if($this->isinpage_pid($page_pid,$allcontent_org[$data_exp[$z]],$alluid_page)==false && $domainCount!=1) 
																{
																	if(in_array($data_exp[$z],$all_refindex) && $flexpointer[$data_exp[$z]]=='sDEF/lDEF/'.$field_array[$i].'/vDEF/' && in_array($this->ttcontent_pid($data_exp[$z]),$alluid_page))
																	{
																	
																	}
																	else
																	{
																		if(in_array($data_exp[$z],$all_refindex) && $flexpointer[$data_exp[$z]]!='sDEF/lDEF/'.$field_array[$i].'/vDEF/') $rep_data[]=$allcontent_org[$data_exp[$z]];
																		//2
																	}
																}
																else
																{
																	if($flexpointer[$data_exp[$z]]!='sDEF/lDEF/'.$field_array[$i].'/vDEF/') $rep_data[]=$allcontent_org[$data_exp[$z]];
																	//else 	$rep_data[]=$allcontent_org[$data_exp[$z]];
																	//3
																}
															}
														}
													}
												}
											}
											if(stristr($field_array[$i],'field_link')) if($all_orguid[$data_exp[$z]]!='') $rep_data[]=$all_orguid[$data_exp[$z]]; 
											
											
													
											if(stristr($field_array[$i],'field_image'))

											{
												
												if(!is_file($path.'uploads/tx_templavoila/'.$all_orguid[$data_exp[$z]])) 
												{
													
													$randtitle=md5(time()).rand(0,9);
													$randtitle=substr($randtitle,0,3);
													//print_r($path.'uploads/tx_templavoila/'.$randtitle.$data_exp[$z]);
													$this->copy_r($setpath.'/tvupload_files/'.$data_exp[$z],$path.'uploads/tx_templavoila/'.$randtitle.$data_exp[$z]);
													$rep_data[]=$randtitle.$data_exp[$z];
												}
												else
												{
													//$randtitle=substr(0,3,md5(time()).rand(0,9));
													//$this->copy_r($setpath.'/tvupload_files/'.$randtitle.$all_orguid[$data_exp[$z]],$path.'uploads/tx_templavoila/'.$randtitle.$all_orguid[$data_exp[$z]]);
													$rep_data[]=$data_exp[$z];
												}
											}																
										}
										if(!stristr($field_array[$i],'field_text') && !stristr($field_array[$i],'field_image'))
										{
											$replace = '<value index="vDEF">'.implode(',',$rep_data).'</value>';
											$search = '<value index="vDEF">'.$data_val.'</value>';			
											
											//print_r($replace); print_r($search.'----------------'."\n");
																		
											if(implode(',',$rep_data)!='') $row['tx_templavoila_flex']=str_replace($search, $replace, $row['tx_templavoila_flex']);
										}else $is_string=1;										
									}
								}
							}
							$old_data=implode(',',$set_old_data);
						}
							
						$update=array(
							'tx_templavoila_flex'	=>	$row['tx_templavoila_flex']
						);

						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$row['uid'],$update);
						$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);										
						
					}
				}
				
			}
			function ttcontent_pid($uid)
			{
				$where = 'deleted=0 AND uid='.$uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{	
					return $row['pid'];
				}
			}
			function isinpage_pid($pid,$uid,$alluid_page)
			{
				//print_r($pid.'-'.$uid.'=');
			
				$where = 'deleted=0 AND pid IN('.implode(',',$alluid_page).') AND uid='.$uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{	
					if($row['pid']!=$pid) return false;
					else return true;
				}
				//print_r($uid."\n");
				return false;
			}	
			function ttcontentall_refindex($tt_content_uid)
			{
			
				$where = 'tablename="tt_content" AND ref_table="tt_content" AND recuid='.$tt_content_uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('ref_uid','sys_refindex',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{	
					$add[]=$row['ref_uid'];					
				}
				return $add;
			}
			function pageall_refindex($page_uid)
			{
			
				$where = 'tablename="pages" AND ref_table="tt_content" AND recuid='.$page_uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('ref_uid,flexpointer','sys_refindex',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{	
					$add[]=$row['ref_uid'];	
					$flexpointer[$row['ref_uid']]=$row['flexpointer'];				
				}
				return array($add,$flexpointer);
			}
			
			function get_org_uidcontent($pid)
			{
				$where = 'pid IN('.implode(',',$pid).')';
				
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,t3_origuid,tx_mtwebmenager_mtorguid ','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					if($row['tx_mtwebmenager_mtorguid']!='' && $row['tx_mtwebmenager_mtorguid']!=0) $uid[str_replace('@','',$row['tx_mtwebmenager_mtorguid'])]=$row['uid'];
					else  $uid[$row['t3_origuid']]=$row['uid'];
				}
				return $uid;
			}
			function tv_getds_true($ds,$to)
			{
				$where = 'deleted=0 AND uid='.$to;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('datastructure','tx_templavoila_tmplobj',$where,'','',1);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					if($ds!=$row['datastructure']) return $row['datastructure'];
					else return $ds;
				}
			}
			function update_org_tv($uid,$org_tx_templavoila_datastructure,$org_tx_templavoila_tmplobj,$tx_templavoila_datastructure,$tx_templavoila_tmplobj)
			{
				$where = 'deleted=0 AND hidden=0 AND uid='.$uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_templavoila_ds,tx_templavoila_to,tx_templavoila_next_ds,tx_templavoila_next_to','pages',$where,'','',1);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$tx_templavoila_ds=$this->get_ifis_tv($row['tx_templavoila_ds'],$org_tx_templavoila_datastructure,$tx_templavoila_datastructure);
					$tx_templavoila_to=$this->get_ifis_tv($row['tx_templavoila_to'],$org_tx_templavoila_tmplobj,$tx_templavoila_tmplobj);
					
					if($tx_templavoila_to!=0 && $tx_templavoila_to!='') $tx_templavoila_ds=$this->tv_getds_true($tx_templavoila_ds,$tx_templavoila_to);

					
					$tx_templavoila_next_ds=$this->get_ifis_tv($row['tx_templavoila_next_ds'],$org_tx_templavoila_datastructure,$tx_templavoila_datastructure);
					$tx_templavoila_next_to=$this->get_ifis_tv($row['tx_templavoila_next_to'],$org_tx_templavoila_tmplobj,$tx_templavoila_tmplobj);
					
					if($tx_templavoila_next_to!=0 && $tx_templavoila_next_to!='') $tx_templavoila_next_ds=$this->tv_getds_true($tx_templavoila_next_ds,$tx_templavoila_next_to);

					$update=array(
						'tx_templavoila_ds'			=>	$tx_templavoila_ds,
						'tx_templavoila_to'			=>	$tx_templavoila_to,
						'tx_templavoila_next_ds'	=>	$tx_templavoila_next_ds,
						'tx_templavoila_next_to'	=>	$tx_templavoila_next_to
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$uid,$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
			}
			function get_ifis_tv($uid,$org,$newuid)
			{
				if(in_array($uid,$org) && $uid!=0)
				{
					return $newuid[$uid];
				}else return 0;
			}
			function get_fe_groups($pid)
			{
				$where = 'deleted=0 AND pid='.$pid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,description','fe_groups',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
				
					if(stristr($row['description'],'{['))
					{
						list(,$return)=explode('{[',$row['description']);
						list($return)=explode(']}',$return);
						
						$update=array(
							'description'	=>	str_replace('{['.$return.']}','',$row['description'])
						);
						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('fe_groups','uid='.$row['uid'],$update);
						$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
						$uid=$row['uid'];
					}
				}
				return array($return,$uid);
			}
			function import_ts($id,$config,$constans,$name,$www,$path,$isroot=0)
			{

				$mt_val_author=addslashes($_POST['mt_val_author']);
				$mt_val_copyright=addslashes($_POST['mt_val_copyright']);
				$mt_val_sitename=addslashes($_POST['mt_val_sitename']);
							
				$constans_name=array(
					'domain'	=>	$www,
					'author'	=>	$mt_val_author,
					'copyright'	=>	$mt_val_copyright,
					'path'		=>	$path
				);
				$constans_key=array_keys($constans_name);
				$constans_value=array_values($constans_name);
				
				for($i=0; $i<count($constans_name); $i++)
				{
					$val=$constans_value[$i];
					$constans[$constans_key[$i]]=$val;
				}
				if($isroot==1)
				{
					$constans['plugin.']['tx_srfeuserregister_pi1.']['siteName']=$mt_val_sitename;	
					$constans['plugin.']['tx_srfeuserregister_pi1.']['email']='support@'.$www;
					
					$update=array(
						'title'	=>	$www
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$id,$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
					
					
					if($constans['mtgenerate_websecode']=='genmynew_code') $constans['mtgenerate_websecode']=$this->genwebsecode();
					
				}
			
			
				return array($config,$constans);
			}
			function genwebsecode()
			{
				$ar=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','r','s','t','u','w','x','y','z');
				$spec=array('!','#','$','%','^','&','*','(',')','_','+','|');				
				
				for($i=0; $i<20; $i++)
				{
					$rand=rand(0,2);
					switch($rand)
					{
						case '0':
							if(rand(0,2)==1) $add[]=$ar[rand(0,count($ar)-1)];	
							else $add[]=strtoupper($ar[rand(0,count($ar)-1)]);
						break;
						case '1':
							if(rand(0,5)==2) 
							{
								$specrand=$spec[rand(0,count($spec)-1)];
								$add[]=$specrand.$specrand;
							}
							else $add[]=$spec[rand(0,count($spec)-1)];
						break;
						case '2':
							$add[]=rand(0,5555);
						break;
					}
				}
				return implode('',$add).time();
				
			}
			function chmod_R($path, $filemode, $dirmode) {
				if (is_dir($path) ) {
					if (!chmod($path, $dirmode)) {
						$dirmode_str=decoct($dirmode);
						print "Failed applying filemode '$dirmode_str' on directory '$path'\n";
						print "  `-> the directory '$path' will be skipped from recursive chmod\n";
						return;
					}
					$dh = opendir($path);
					while (($file = readdir($dh)) !== false) {
						if($file != '.' && $file != '..') {  // skip self and parent pointing directories
							$fullpath = $path.'/'.$file;
							chmod_R($fullpath, $filemode,$dirmode);
						}
					}
					closedir($dh);
				} else {
					if (is_link($path)) {
						print "link '$path' is skipped\n";
						return;
					}
					if (!chmod($path, $filemode)) {
						$filemode_str=decoct($filemode);
						print "Failed applying filemode '$filemode_str' on file '$path'\n";
						return;
					}
				}
			} 
			function mtweb_install()
			{
				global $LANG;
				$error=0;
				$www=addslashes(str_replace(' ','',$_POST['mtweb_www']));
				$web_path=str_replace(' ','_',strip_tags(addslashes($_POST['mtweb_path'])));
				$pid=intval($_POST['mtweb_pid']);
				$file=array_keys($_POST['installmtweb']);
				$file=$file[0];
				list($pack_name)=explode('.zip',$file);
				if(stristr($file,'.zip'))
				{
					$path=$_SERVER['DOCUMENT_ROOT'];
					if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
					$path=$path.'fileadmin/templates/'.$web_path;
					
					if(function_exists('system')) system('mkdir '.$path);
					else mkdir($path,0777);
					

					if(is_dir($path))
					{
						$this->chmod_R($path,0755,0757);
						$file_path=$_SERVER['DOCUMENT_ROOT'];
						if($file_path!='/') $file_path=$file_path.'/';
						$pack_file=$path.'/'.$pack_name.'.t3d';
						$file_path=$file_path.'fileadmin/mtwebmenager/'.$file;
						
						if(function_exists('system')) system('unzip -q '.$file_path.' -d '.$path);
						else
						{
							 $zip = new ZipArchive;
							 $res = $zip->open($file_path);
							 if ($res === TRUE) {
								 $zip->extractTo($path);
								 $zip->close();
							 } else {
								 $error=1;
							 }
						}
						
						if(is_dir($path) && $error==0)
						{								
							//$this->chmod_R($path, 777, 777);
							
							$js="
							<script language=\"javascript\" type=\"text/javascript\">
								document.getElementById('mt_process_1').onload= function() {
										document.getElementById('mt_import_finish_load').style.display='none';
										document.getElementById('mt_import_finish').style.display='block';
								};
							</script>
							";
							return '
							<h1>Install proces 1 from 2</h1>
							<iframe src="/typo3/sysext/impexp/app/index.php?id='.$pid.'&table=pages&tx_impexp[action]=import&tx_impexp[file]='.$pack_file.'&tx_impexp[import_file]=Import" id="mt_process_1"></iframe>
							
							<div id="mt_import_finish_load">
								'.$LANG->getLL('text_import_loading').' <img src="/typo3conf/ext/mt_webmenager/ajax-loader.gif" title="Łagowanie..." />		 				
							</div>
								
							<div id="mt_import_finish">
								<h2>'.$LANG->getLL('text_import_finish_header').'</h2>
								
								<label>'.$LANG->getLL('mt_val_author').'</label> <input name="mt_val_author" type="text" /><br />
								<label>'.$LANG->getLL('mt_val_copyright').'</label> <input name="mt_val_copyright" type="text" /><br />
								<label>'.$LANG->getLL('mt_val_sitename').'</label> <input name="mt_val_sitename" type="text" /><br />
								
								<input name="mt_pack_name" type="hidden" value="'.$pack_name.'" />
								<input name="mt_pack_www" type="hidden" value="'.$www.'" />
								<input name="mt_page_path" type="hidden" value="'.$web_path.'" />
								<input name="mt_pack_pid" type="hidden" value="'.$pid.'" />
								
								<input name="mt_finish_all" type="submit" value="Finish import" />
							</div>
							
							'.$js;
						}else if($error==0) return'no path name'; else return'cant unzip file';
					}else return 'no fileadmin folder';
				}
				
				return 'install';
			}
			function set_orguid($val,$all_orguid)
			{
				$return=array();
				for($i=0; $i<count($val); $i++)
				{
					if($all_orguid[$val[$i]]!='') $return[]=$all_orguid[$val[$i]];
				}
				
				return $return;
			}
			function get_orguid($uid)
			{
				$where = 'deleted=0 AND hidden=0 AND uid='.$uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('t3_origuid,tx_mtwebmenager_mtorguid ','pages',$where,'','',1);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					if($row['tx_mtwebmenager_mtorguid']!='' && $row['tx_mtwebmenager_mtorguid ']!=0) $t3_origuid=str_replace('@','',$row['tx_mtwebmenager_mtorguid']);
					else $t3_origuid=$row['t3_origuid'];
				}
				return $t3_origuid;
			}
			function parse_ts_tostring($constans,$old_constans,$root='',$import='',$all_orguid,$get_fe_groups=array(),$tt_news_cat_org_uid=array())
			{
				$next_nr=0;
				$mt_check_name=array(
					'mt_fe_groups',
					'mt_pages',
					'mt_tt_content',
					'mt_ttnews',
					'mt_tt_news_cat'
				);

				$ex_constans=explode("\n",$old_constans);
				for($i=0; $i<count($ex_constans); $i++)
				{
					$ex_val=$ex_constans[$i];
					if(!stristr($ex_val,'#') && !stristr($ex_val,'<')) 
					{
						if(stristr($ex_val,'='))
						{
							list($ts_name,$ts_val)=explode('=',$ex_val);
								$ts_val=str_replace(chr(13),'',$ts_val);
								$ts_name=str_replace(chr(13),'',$ts_name);
							$check_name[]=str_replace(' ','',$ts_name);
							$check_val[]=str_replace(' ','',$ts_val);
							$true_name[]=$ts_name;
							$true_val[]=$ts_val;
							$name_number[str_replace(' ','',$ts_name)]=$next_nr;
							$next_nr++;
						}
					}
				}
				

				$constans=t3lib_BEfunc::implodeTSParams($constans);
				$constans_key=array_keys($constans);
					//print_r($constans_key);
				
				for($i=0; $i<count($constans_key); $i++)
				{
					$arr_name=$name_number[$constans_key[$i]];

					if($check_val[$arr_name]!=$constans[$constans_key[$i]]) 
					{				
						//print_r($check_name[$arr_name]."\n");
						if($true_val[$arr_name]!='') 
						{
							$old_constans=str_replace($true_name[$arr_name].'='.$true_val[$arr_name],$constans_key[$i].'='.$constans[$constans_key[$i]],$old_constans);


						}
					}					
				}
		
				if($root!='')
				{
		
					$ex_constans=explode("\n",$old_constans);
					for($i=0; $i<count($ex_constans); $i++)
					{
						$dont_check=0;
						$ex_val=$ex_constans[$i];
						if(!stristr($ex_val,'#')) 
						{
	
							if(stristr($ex_val,'=') && !stristr($ex_val,'###MT_DONT_PARS###'))
							{
								$is_int=0;
														
								list($ts_name,$ts_val)=explode('=',$ex_val);
								$ts_val=str_replace(chr(13),'',$ts_val);
								$ts_name=str_replace(chr(13),'',$ts_name);
								$check_name=str_replace(' ','',$ts_name);
								$check_val=str_replace(' ','',$ts_val);
								$true_name=$ts_name;
								$true_val=$ts_val;
								
								foreach($mt_check_name as $key => $search_needle) 
								{
								
								
								   if(stristr($check_name, $search_needle) != FALSE) 
								   {
								   		
										switch($search_needle)
										{
											case 'mt_fe_groups':
												 $old_constans=str_replace($true_name.'='.$true_val,$true_name.'='.$get_fe_groups[$true_val],$old_constans);
											break;
											
											case 'mt_pages':
												$old_constans=str_replace($true_name.'='.$true_val,$true_name.'='.$all_orguid[$true_val],$old_constans);
											break;
											
											case 'mt_tt_content':
												$tt_content_org_uid=$this->tt_content_org_uid($all_orguid,$true_val);
												$old_constans=str_replace($true_name.'='.$true_val,$true_name.'='.$tt_content_org_uid,$old_constans);
											break;
											
											case 'mt_ttnews':
												$tt_news_org_uid=$this->tt_news_org_uid($all_orguid,$true_val);
												$old_constans=str_replace($true_name.'='.$true_val,$true_name.'='.$tt_news_org_uid,$old_constans);
											break;
											
											case 'mt_tt_news_cat':
												if(stristr($true_val,','))
												{
												
													$mt_tt_news_cat_array=explode(',',$check_val);
													//print_r(count($mt_tt_news_cat_array));print_r('--------');
													
													for($z=0; $z<count($mt_tt_news_cat_array); $z++)
													{
														$mt_tt_news_cat_new[]=$tt_news_cat_org_uid[$mt_tt_news_cat_array[$z]];
													}
													
													
													$old_constans=str_replace($true_name.'='.$true_val,$true_name.'='.implode(',',$mt_tt_news_cat_new),$old_constans);
													
												}else $old_constans=str_replace($true_name.'='.$true_val,$true_name.'='.$tt_news_cat_org_uid[$check_val],$old_constans);											
											break;
										}
										 $dont_check=1;
								   }
								
								} 
								
								
								if($dont_check==0)
								{

									if(stristr($check_val,','))
									{
										$check_val=explode(',',$check_val);
										for($z=0; $z<count($check_val); $z++)
										{
											if(intval($check_val[$z])!=0 || $check_val[$z]=='0') $is_int=1;
											else $is_int=0;
										}
									}else
									{
											
										if(intval($check_val)!=0 || $check_val=='0') 
										{
											$is_int=1;
											$check_val=array($check_val);
										}
									}
								
									if($is_int==1)
									{
										$get_val=$this->set_orguid($check_val,$all_orguid);
										$get_val=implode(',',$get_val);
										$old_constans=str_replace($true_name.'='.$true_val,$true_name.'='.$get_val,$old_constans);
									}
								}
								
							}
						}else if(stristr($ex_val,'###MT_DONT_PARS###')) { $i=count($ex_constans); break; }
					}
				}
				//print_r('f'.time());
				//exit;
				//exit;
				//print_r($old_constans.'@@@@@@@@@@@');
				return $old_constans;		
			}
			function tt_news_org_uid($pid,$val)
			{
				$where = 't3_origuid='.$val.' AND pid IN('.implode(',',$pid).')';
				
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tt_news',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$uid=$row['uid'];
				}
				return $uid;
			}
			function tt_content_org_uid($pid,$val)
			{
				$where = 'tx_mtwebmenager_mtorguid='.$val.' AND pid IN('.implode(',',$pid).')';
				
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$uid=$row['uid'];
				}
				if($uid=='' || $uid==0)
				{
					$where = 't3_origuid='.$val.' AND pid IN('.implode(',',$pid).')';
					
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tt_content',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$uid=$row['uid'];
					}
				}
				return $uid;
			}
			function add_zip($file,$folder)
			{
				$last=explode('/',$folder);
				$last=$last[count($last)-1].'/';
				
				$zip = new ZipArchive();
				$zip->open($file, ZipArchive::CREATE);
				
				$dirName = $folder;
				
				if (!is_dir($dirName)) {
					throw new Exception('Directory ' . $dirName . ' does not exist');
				}
				
				$dirName = realpath($dirName);
				
				if (substr($dirName, -1) != '/') {
					$dirName.= '/';
				}
				
				/*
				 * NOTE BY danbrown AT php DOT net: A good method of making
				 * portable code in this case would be usage of the PHP constant
				 * DIRECTORY_SEPARATOR in place of the '/' (forward slash) above.
				 */
				
				$dirStack = array($dirName);
				//Find the index where the last dir starts
				$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;
				
				while (!empty($dirStack)) {
					$currentDir = array_pop($dirStack);
					
					$filesToAdd = array();
				
					$dir = dir($currentDir);
					while (false !== ($node = $dir->read())) {
						if (($node == '..') || ($node == '.')) {
							continue;
						}
						if (is_dir($currentDir . $node)) {
							array_push($dirStack, $currentDir . $node . '/');
						}
						if (is_file($currentDir . $node)) {
							$filesToAdd[] = $node;
						}
					}
				
					$localDir = substr($currentDir, $cutFrom);
					$localDir=str_replace($last,'',$localDir);
					$zip->addEmptyDir($localDir);
				   
					foreach ($filesToAdd as $file) {
						$zip->addFile($currentDir . $file, $localDir . $file);
					}
					
				}
				
				$zip->close(); 
			}
			function finish_export($repair='',$repair_array=array())
			{
				global $LANG;
				
				if($repair!='')
				{
					$_POST['mt_pack_name']=$repair_array[0];
					//$_POST['mt_pack_name']=$repair_array[0];
					$_POST['mt_tmp_folder']=$repair_array[2];
					$_POST['mt_old_all']=$repair_array[3];
				}
				
				$name=$_POST['mt_pack_name'];
				$mt_tmp_folder=$_POST['mt_tmp_folder'];
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
				$path_mtwebmenager=$path.'fileadmin/mtwebmenager/';
				
				if(!is_file($path_mtwebmenager.$name.'.zip'))
				{
					if(function_exists('system'))
					{
						system('cd '.$path.'fileadmin/ ; zip -r -q '.$path_mtwebmenager.$name.'.zip '.$name.'.t3d');
						system('cd '.$mt_tmp_folder.' ; zip -r -q '.$path_mtwebmenager.$name.'.zip *');
						system('rm -R '.$mt_tmp_folder);
					}
					else
					{
						copy($path.'fileadmin/'.$name.'.t3d',$mt_tmp_folder.'/'.$name.'.t3d');
						$this->add_zip($path_mtwebmenager.$name.'.zip',$mt_tmp_folder);
						rmdir($mt_tmp_folder);
					}
					$old_dane=unserialize(base64_decode($_POST['mt_old_all']));
					
					$constans=$old_dane['constans'];
					//$config=$this->parse_ts_tostring($old_dane['config']);	
					
					$this->update_rootext($old_dane['sys_template_uid'],$constans,$config);
					
					$update=array(
						'title'	=>	$old_dane['title']
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$old_dane['page_uid'],$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
					
					$this->update_domainName($old_dane['domainName'],$old_dane['domainNameUid']);
					//page_uid
					$page_uid=$old_dane['page_uid'];
					$alluid=$this->get_pagetree($page_uid);
					$old_path=$old_dane['path'];
					
					for($i=0; $i<count($alluid); $i++)
					{
						$reback_uid=$alluid[$i]['row']['uid'];
						$this->update_content_orguid_import($reback_uid,'{$mtpathimport}',$old_path);
						
						$where = 'deleted=0 AND pid='.$reback_uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,description','fe_groups',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							if(stristr($row['description'],']}'))
							{
								list(,$row['description'])=explode(']}',$row['description']);
								$update=array(
									'description'	=>	$row['description']
								);
								$query = $GLOBALS['TYPO3_DB']->UPDATEquery('fe_groups','uid='.$row['uid'],$update);
								$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
							}
						}
					}
					
					$storage_pid=$old_dane['storage_pid'];			
					
					$where = 'deleted=0 AND pid='.$storage_pid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,description','tt_news_cat',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						if(stristr($row['description'],']}'))
						{
							list(,$row['description'])=explode(']}',$row['description']);
							$update=array(
								'description'	=>	$row['description']
							);
							$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_news_cat','uid='.$row['uid'],$update);
							$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
						}
					}
						
					$where = 'deleted=0 AND pid='.$storage_pid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_templavoila_datastructure',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$update=array(
							't3_origuid'	=>	'0',
							'tx_mtwebmenager_mtorguid'	=>	'0'
						);
						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_templavoila_datastructure','uid='.$row['uid'],$update);
						$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
					}	
					$where = 'deleted=0 AND pid='.$storage_pid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_templavoila_tmplobj',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$update=array(
							't3_origuid'	=>	'0',
							'tx_mtwebmenager_mtorguid'	=>	'0'
						);
						$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_templavoila_tmplobj','uid='.$row['uid'],$update);
						$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
					}
					$update=array(
						't3_origuid'	=>	'0',
						'tx_mtwebmenager_mtorguid'	=>	'0'
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid!=0',$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
					$update=array(
						't3_origuid'	=>	'0',
						'tx_mtwebmenager_mtorguid'	=>	'0'
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_content','uid!=0',$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);						
						
					//storage_pid
					$this->tvobj_file_rename($old_dane['storage_pid'],'{$mtpathimport}',$old_path);	
					
					t3lib_BEfunc::openPageTree(0);
					t3lib_BEfunc::setUpdateSignal('updatePageTree');
					$js="
					<script language=\"javascript\" type=\"text/javascript\">
							".t3lib_BEfunc::getUpdateSignalCode()."
					</script>
					";
					
					//$query = $GLOBALS['TYPO3_DB']->DELETEquery('tx_mtwebmenager_sys_refindex', 'uid!=0');		
					//$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);	
					
					unlink($path_mtwebmenager.'mtcache/'.$name.'ext.mtcache');
					
					return '
						<h2>'.$LANG->getLL('text_export_is_finish').'</h2>	
						'.$LANG->getLL('text_export_download').' <b><a href="/fileadmin/mtwebmenager/'.$name.'.zip">download</a></b>
					'.$js;
				}
			}
			function tx_tvis_truname($ds,$to)
			{
				$where = 'deleted=0 AND uid='.$ds;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('title','tx_templavoila_datastructure',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$title_ds=$row['title'];
				}	
				$where = 'deleted=0 AND uid='.$to;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('title','tx_templavoila_tmplobj',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$title_to=$row['title'];
				}	
				//print_r($title_ds.'-'.$title_to."\n");
				if($title_ds==$title_to) return false;
				else return true;
			}
			function gettx_templavoila_to($mtto)
			{
				//print_r($mtto.',');
				$where = 'deleted=0 AND tx_mtwebmenager_mtorguid="@'.$mtto.'" OR deleted=0 AND tx_mtwebmenager_mtorguid="'.$mtto.'"';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,datastructure','tx_templavoila_tmplobj',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$to=$row['uid'];
					$ds=$row['datastructure'];
				}		
				return array($to,$ds);
			}
			function update_content_orguid_import($uid,$name,$old_name,$org_tx_templavoila_datastructure='',$org_tx_templavoila_tmplobj='',$tx_templavoila_datastructure='',$tx_templavoila_tmplobj='')
			{

				$where = 'pid='.$uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pi_flexform,tx_templavoila_ds,tx_templavoila_to','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					if(1==1)
					{
						//$tx_templavoila_ds=$this->get_ifis_tv($row['tx_templavoila_ds'],$org_tx_templavoila_datastructure,$tx_templavoila_datastructure);
						//$tx_templavoila_to=$this->get_ifis_tv($row['tx_templavoila_to'],$org_tx_templavoila_tmplobj,$tx_templavoila_tmplobj);
						list($tx_templavoila_to,$tx_templavoila_ds)=$this->gettx_templavoila_to($row['tx_templavoila_to']);
						
						//$this->tx_tvis_truname($tx_templavoila_ds,$tx_templavoila_to);
						
						//if($this->tx_tvis_truname($tx_templavoila_ds,$tx_templavoila_to)) $tx_templavoila_ds=$tx_templavoila_to;
						$update=array(
	
							'tx_templavoila_ds'	=>	$tx_templavoila_ds,
							'tx_templavoila_to'	=>	$tx_templavoila_to,
							'pi_flexform'		=>	str_replace($name,$old_name,$row['pi_flexform'])
						);
					}
					else
					{
						$update=array(
	
							//'t3_origuid'	=>	$row['uid'],
							'pi_flexform'	=>	str_replace($name,$old_name,$row['pi_flexform'])
						);
					}

					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_content','uid='.$row['uid'],$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
			}
			function get_export_param($param)
			{
				foreach($param as $val)
				{
					$add[]='tx_impexp[pagetree][tables][]='.$val;
				}
				return implode('&',$add);
			}
			function get_export_start()
			{
				global $LANG;
				
				$export_table=array(
				'sys_language',
				'sys_news',
				'tt_content',
				'fe_groups',
				'sys_domain',
				'sys_template',
				'sys_action',
				'tx_rtehtmlarea_acronym',
				'static_template',
				'tx_templavoila_tmplobj',
				'tx_templavoila_datastructure',
				'tx_mtwebmenager_sys_refindex',
				'tx_mtwq_dsa'
				);
				$relation_table=array(
				'pages',
				'sys_language',
				'sys_news',
				'tt_content',
				'fe_groups',
				'sys_domain',
				'sys_template',                           
				'sys_action',
				'tx_rtehtmlarea_acronym',
				'static_template',
				'tx_templavoila_tmplobj',
				'tx_templavoila_datastructure',
				'tx_mtwebmenager_sys_refindex',
				'tx_mtwq_dsa'
				);

				
				/*
								
								export tt_news (article) <input name="mt_add_export_ttnews" type="checkbox" value="1" /><br />
								export cat_tt_news (category in article) <input name="mt_add_export_catttnews" type="checkbox" value="1" /><br />
								export mt link? (swl) <input name="mt_add_export_mtlink" type="checkbox" value="1" /><br />
				
				*/
				
				if(isset($_POST['mt_add_export_ttnews'])) 
				{
					$export_table[]='tt_news';
					$relation_table[]='tt_news';
				}
				if(isset($_POST['mt_add_export_catttnews'])) 
				{
					$export_table[]='tt_news_cat';
					$relation_table[]='tt_news_cat';
				}
				if(isset($_POST['mt_add_export_mtlink'])) 
				{
					$export_table[]='tx_mtelink_link';
					$relation_table[]='tx_mtelink_link';
				}
				
				$pagetree=$this->get_export_param($export_table,'tx_impexp[pagetree][tables][]');
				$external_ref=$this->get_export_param($relation_table,'&tx_impexp[external_ref][tables][]');
				$external_static=$this->get_export_param($relation_table,'tx_impexp[external_static][tables][]');
				
						
				$count_root=0;
				$id=intval($_POST['mt_page_uid']);
				$name=str_replace(' ','_',$_POST['mt_export_name']);
				
					$path=$_SERVER['DOCUMENT_ROOT'];
					if($path!='/' && substr($path,-1)!='/') $path=$path.'/';					
					$path_mtwebmenager=$path.'fileadmin/mtwebmenager/';	
					
				if(is_file($path_mtwebmenager.'mtcache/'.$name.'ext.mtcache'))
				{
					return $this->show_error_view($LANG->getLL('text_export_error_cache_exists'));
				}
					
				if(isset($_POST['mt_overwrite_template']))
				{								
					if(is_file($path_mtwebmenager.$name.'.zip'))
					{
						unlink($path_mtwebmenager.$name.'.zip');
					}
				}
				
				if($name!='')
				{
					$where = 'deleted=0 AND hidden=0 AND pid='.$id.' AND is_siteroot=1';
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,storage_pid','pages',$where,'','');
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$root_uid=$row['uid'];	
						$storage_pid=$row['storage_pid'];
						$count_root++;
					}
					$where = 'hidden=0 AND pid='.$root_uid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,domainName','sys_domain',$where,'','',1);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$domainName=$row['domainName'];
						$domainNameUid=$row['uid'];
					}
					$where = 'deleted=0 AND hidden=0 AND uid='.$id;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('title','pages',$where,'','',1);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$title=$row['title'];
					}
					if($root_uid!='' && $count_root==1)
					{						
					
						$where = 'deleted=0 AND pid='.$storage_pid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_templavoila_datastructure',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$update=array(
								't3_origuid'				=>	$row['uid'],
								'tx_mtwebmenager_mtorguid'	=>	'@'.$row['uid']
							);
							$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_templavoila_datastructure','uid='.$row['uid'],$update);
							$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
						}	
						$where = 'deleted=0 AND pid='.$storage_pid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tx_templavoila_tmplobj',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$update=array(
								't3_origuid'				=>	$row['uid'],
								'tx_mtwebmenager_mtorguid'	=>	'@'.$row['uid']
							);
							$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_templavoila_tmplobj','uid='.$row['uid'],$update);
							$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
						}
					
						$where = 'deleted=0 AND hidden=0 AND pid='.$root_uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,constants,config','sys_template',$where,'','',1);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$constans = $this->parseTS($row['constants']);
							//$config = $this->parseTS($row['config']);
							$path=$constans['path'];
							list($folder_tmp,$error)=$this->get_folder_tmp($path,$name);
							if($folder_tmp!='')
							{
								$alluid=$this->get_pagetree($id);
								$this->flex_content_checker($alluid,$folder_tmp);
								$this->update_orguid($alluid,$id,$path,$export_table);
								
								//$old_config=$config;
								$old_constans=$row['constants'];
								
								list($config,$constans)=$this->rename_all($id,$config,$constans,$name);

								$constans=$this->parse_ts_tostring($constans,$row['constants']);

								//$config=$this->parse_ts_tostring($config);	
								
								$this->update_rootext($row['uid'],$constans,$config);			
								$this->update_domainName('domain.com',$domainNameUid);					
								$this->tvobj_file_rename($storage_pid,$path,'{$mtpathimport}');
								$old_array=array(
									'path'				=>	$path,
									'sys_template_uid'	=>	$row['uid'],
									'title'				=>	$title,
									//'config'			=>	$old_config,
									'constans'			=>	$old_constans,
									'domainName'		=>	$domainName,
									'domainNameUid'		=>	$domainNameUid,
									'page_uid'			=>	$id,
									'storage_pid'		=>	$storage_pid
								);
								$old_all=serialize($old_array);
								$old_all=base64_encode($old_all);

									
								for($i=0; $i<count($alluid); $i++)
								{
									$isuid=$alluid[$i]['row']['uid'];
									$allisuid[]=$isuid;
									$update=array(
										'tx_mtwebmenager_mtorguid'	=>	'@'.$isuid
									);
									$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$isuid,$update);
									$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
									
									$where = 'deleted=0 AND pid='.$isuid;
									$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tt_content',$where);
									while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
									{
										$update=array(
											'tx_mtwebmenager_mtorguid'	=>	'@'.$row['uid']
										);
										$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_content','uid='.$row['uid'],$update);
										$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
									}
															
								}
								//$this->addall_refindex_org($allisuid,$root_uid);

								t3lib_BEfunc::openPageTree(0);
								t3lib_BEfunc::setUpdateSignal('updatePageTree');
								$js="
								<script language=\"javascript\" type=\"text/javascript\">
									document.getElementById('mt_export_par1').onload= function() {
										".t3lib_BEfunc::getUpdateSignalCode()."
										document.getElementById('mt_export_finish_load').style.display='none';
										document.getElementById('mt_export_finish').style.display='block';
									};
								</script>
								";
									
									$cache_open=fopen($path_mtwebmenager.'mtcache/'.$name.'ext.mtcache',"w+");
									$cache_array=array(
										$name,
										$id,
										$folder_tmp,
										$old_all
									);
									$cache_array=serialize($cache_array);
									$cache_array=base64_encode($cache_array);
									fwrite($cache_open,$cache_array);
									fclose($cache_open);
									
								return '
								<h1>Export proces 2 from 2aaaaaaaaaa</h1>
								
								<iframe src="/typo3/sysext/impexp/app/index.php?tx_impexp[action]=export&id='.$id.'&tx_impexp[pagetree][id]='.$id.'&tx_impexp[pagetree][levels]=0&tx_impexp[pagetree][tables][]='.$pagetree.'&tx_impexp[pagetree][maxNumber]=1000&tx_impexp[pagetree][levels]=999&tx_impexp[external_ref][tables][]='.$external_ref.'&tx_impexp[external_static][tables][]='.$external_static.'&tx_impexp[maxFileSize]=10000&tx_impexp[filename]='.$name.'&tx_impexp[save_export]=Save to filename" id="mt_export_par1"></iframe>
								
								<div id="mt_export_finish_load">
									'.$LANG->getLL('text_export_loading').'	<img src="/typo3conf/ext/mt_webmenager/ajax-loader.gif" title="Łagowanie..." />					
								</div>
									
								<div id="mt_export_finish">
									<h2>'.$LANG->getLL('text_export_finish_header').'</h2>
									
									<input name="mt_pack_name" type="hidden" value="'.$name.'" />
									<input name="mt_page_reback_uid" type="hidden" value="'.$id.'" />
									<input name="mt_tmp_folder" type="hidden" value="'.$folder_tmp.'" />
									<input name="mt_old_all" type="hidden" value="'.$old_all.'" />
									
									<input name="mt_finish_all" type="submit" value="Finish export" />
									
								</div>
								'.$js;
										


								
								
							}else return $error;
						}
					}elseif($count_root==0) return $this->show_error_view($LANG->getLL('text_export_error_uidnoroot')); else return $this->show_error_view($LANG->getLL('text_export_error_uidnoroot_more'));	
				}else return $this->show_error_view($LANG->getLL('text_export_error_name_empty'));
			}
			function addall_refindex_org($pid,$root_uid)
			{
				$where = 'deleted=0 AND tablename="pages" AND recuid IN('.implode(',',$pid).') AND ref_table="tt_content"';
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('hash,recuid,ref_uid','sys_refindex',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{	
					//tx_mtwebmenager_sys_refindex
					$add=array(
						'pid'			=>	$root_uid,
						'tstamp'		=>	time(),
						'crdate'		=>	time(),
						'dasd'			=>	rand(0,9),
					);
					$GLOBALS['TYPO3_DB']->exec_INSERTquery(
							'tx_mtwq_dsa',
							$add
					);
				}
			}
			function flex_content_checker($all,$folder_tmp)
			{
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
								
				mkdir($folder_tmp.'/tvupload_files');
				for($i=0; $i<count($all); $i++)
				{
					$all_page_pid[]=$all[$i]['row']['uid'];
				}
				$where = 'pid IN('.implode(',',$all_page_pid).')';
				//print_r($where);
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('header,uid,tx_templavoila_flex ','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{									
					$set_old_data=$rep_data=array();
					if($row['tx_templavoila_flex']!='')
					{
						preg_match_all('/<value index=\"vDEF\">(.*)<\/value>/',$row['tx_templavoila_flex'],$data);
						preg_match_all('/<field index=\"(.*)\">/',$row['tx_templavoila_flex'],$field);
					
						$data_array=$data[1];
						$field_array=$field[1];
						
						//print_r($data_array);
															
						if($data_array!='')
						{
							for($i=0; $i<count($data_array); $i++)
							{
								$data_val=$data_array[$i];
								
								if($data_val!='') 
								{																			
									$rep_data=array();
									if(stristr($field_array[$i],'field_image'))
									{										
										$this->copy_r($path.'uploads/tx_templavoila/'.$data_val,$folder_tmp.'/tvupload_files/'.$data_val);
									}
								}
							}
						}
					}
				}
			}
			function update_domainName($name,$uid)
			{
				$update=array(
					'domainName '	=>	$name
				);
				$query = $GLOBALS['TYPO3_DB']->UPDATEquery('sys_domain','uid='.$uid,$update);
				$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
			}
			function update_content_orguid($uid,$path)
			{
				$where = 'pid='.$uid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pi_flexform','tt_content',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$update=array(
						't3_origuid'	=>	$row['uid'],
						'pi_flexform'	=>	str_replace('templates/'.$path,'templates/{$mtpathimport}',$row['pi_flexform'])
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_content','uid='.$row['uid'],$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
			}
			function update_orguid($all,$id,$path,$export_table=array())
			{
				for($i=0; $i<count($all); $i++)
				{
					$uid=$all[$i]['row']['uid'];
					$update=array(
						't3_origuid'	=>	$uid
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$uid,$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);

					$this->update_content_orguid($uid,$path);
					$this->update_fe_groups($uid);
					
					if(in_array('tt_news',$export_table)) $this->update_tt_news($uid);
					if(in_array('tt_news_cat',$export_table)) $this->update_tt_news_cat($uid);
				}
				// ----------------------------------------------------------------------------
				$update=array(
					't3_origuid'	=>	$id
				);
				$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$id,$update);
				$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
			}
			function update_tt_news($pid)
			{
				$where = 'deleted=0 AND pid='.$pid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','tt_news',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$update=array(
						't3_origuid'	=>	$row['uid']
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_news','uid='.$row['uid'],$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
			}
			function update_tt_news_cat($pid)
			{
				$where = 'deleted=0 AND pid='.$pid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,description','tt_news_cat',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$update=array(
						'description'	=>	'{['.$row['uid'].']}'.$row['description']
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tt_news_cat','uid='.$row['uid'],$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
			}
			function update_fe_groups($pid)
			{
				$where = 'deleted=0 AND pid='.$pid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,description','fe_groups',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$update=array(
						'description'	=>	'{['.$row['uid'].']}'.$row['description']
					);
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('fe_groups','uid='.$row['uid'],$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
			}
			function tvobj_file_rename($pid,$path_name,$tmp_name)
			{
				$where = 'deleted=0 AND pid='.$pid;
				$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,fileref,title','tx_templavoila_tmplobj',$where);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
				{
					$file=str_replace('templates/'.$path_name,'templates/'.$tmp_name,$row['fileref']);
					$update=array('fileref' => $file, 'fileref_md5'=>md5($file));
					$query = $GLOBALS['TYPO3_DB']->UPDATEquery('tx_templavoila_tmplobj','uid='.$row['uid'],$update);
					$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				}
			}
			function update_rootext($uid,$constans,$config)
			{
				$update=array(
					'constants'	=>	$constans,
					//'config'	=>	$config
				);
				$query = $GLOBALS['TYPO3_DB']->UPDATEquery('sys_template','uid='.$uid,$update);
				$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
			}
			function parse_setup_to_TS($setup)
			{
				$TSparserObject = t3lib_div::makeInstance('t3lib_tsparser');
				$some=$TSparserObject->parseSub($setup);
				return $TSparserObject->setup;
			}
			function rename_all($id,$config,$constans,$name)
			{
				$update=array(
					'title'	=>	addslashes($name).'ext'
				);
				$query = $GLOBALS['TYPO3_DB']->UPDATEquery('pages','uid='.$id,$update);
				$set = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
				
				$constans_name=array(
					'domain'	=>	'domain.com',
					'author'	=>	'Your author name',
					'copyright'	=>	'domain.com',
					'path'		=>	addslashes($name)
				);
				$constans_key=array_keys($constans_name);
				$constans_value=array_values($constans_name);
				
				for($i=0; $i<count($constans_name); $i++)
				{
					$constans[$constans_key[$i]]=$constans_value[$i];
				}
				$constans['plugin.']['tx_srfeuserregister_pi1.']['siteName']='Your name config';	
				$constans['plugin.']['tx_srfeuserregister_pi1.']['email']='support@domain.com';
				return array($config,$constans);
			}
			function get_pagetree($uid)
			{
				$tree = t3lib_div::makeInstance('t3lib_pageTree');
				$tree->init('AND '.$GLOBALS['BE_USER']->getPagePermsClause(1));
				$cos = $tree->getTree($uid, 9, '');
				$alltree=$tree->tree;
				return $alltree;
			}
			function copy_r( $path, $dest )
			{
				if( is_dir($path) )
				{
					@mkdir( $dest );
					$objects = scandir($path);
					if( sizeof($objects) > 0 )
					{
						foreach( $objects as $file )
						{
							if( $file == "." || $file == ".." )
								continue;
							// go on
							if( is_dir( $path.DS.$file ) )
							{
								$this->copy_r( $path.DS.$file, $dest.DS.$file );
							}
							else
							{
								copy( $path.DS.$file, $dest.DS.$file );
							}
						}
					}
					return true;
				}
				elseif( is_file($path) )
				{
					return copy($path, $dest);
				}
				else
				{
					return false;
				}
			}
			function get_folder_tmp($get_path,$name)
			{
				global $LANG;
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
				$path_file=$path.'/fileadmin/templates/'.$get_path;
				if(is_dir($path_file))
				{
					$rand_name=md5(time());
					$rand_name=$path.'fileadmin/templates/'.$rand_name;
					if(function_exists('system'))
					{
						system('mkdir '.$rand_name);
						system('chmod 755 -R '.$rand_name);
					}
					else
					{
						mkdir($rand_name,0700);
					}
					
					if(is_dir($rand_name))
					{
						if(function_exists('system'))
						{
							system('cp -R '.$path_file.'/* '.$rand_name.'');
							system('mv '.$rand_name.'/'.$get_path.' '.$rand_name.'/'.$name);
						}
						else
						{
							$this->copy_r($path_file,$rand_name);
							$this->copy_r($rand_name.'/'.$get_path,$rand_name.'/'.$name);
							rmdir($rand_name.'/'.$get_path);
							
						}
						return array($rand_name,'');
						
					}else return array('',$this->show_error_view($LANG->getLL('text_export_error_folderrandom')));
				}else return array('',$this->show_error_view($LANG->getLL('text_export_error_folderpath')));
			}
			function parseTS($tsString)
			{
				$TSparserObject = t3lib_div::makeInstance('t3lib_tsparser');
				$TSparserObject->parse($tsString);
				return $TSparserObject->setup;
			}

			function get_export_part()
			{
				global $LANG;
				$version='alpha 1.0.1';
				
				$id=intval($_POST['mt_page_uid']);
				if($id!=0)
				{
					$where = 'deleted=0 AND hidden=0 AND pid='.$id.' AND is_siteroot=1';
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid','pages',$where,'','',1);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$root_uid=$row['uid'];	
					}
					if($root_uid!='')
					{
						$where = 'deleted=0 AND hidden=0 AND uid='.$id;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('title','pages',$where,'','',1);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$title=$row['title'];
						}
						return $LANG->getLL('text_export_insertname_pack').'
							<br />
							['.$title.'] <input name="mt_export_name" type="text" /> (example: start_myname, social_super_name)
							<input name="mt_overwrite_template" type="checkbox" value="" /> czy chesz nadpisać istniejący szablon?
							<br />
							<input name="mt_page_uid" type="hidden" value="'.$id.'" />
							
							<fieldset class="mt_option">
								<legend>Option</legend>
								
								export tt_news (article) <input name="mt_add_export_ttnews" type="checkbox" value="1" /><br />
								export cat_tt_news (category in article) <input name="mt_add_export_catttnews" type="checkbox" value="1" /><br />
								export mt link? (swl) <input name="mt_add_export_mtlink" type="checkbox" value="1" /><br />
								
							</fieldset>
							<span>Export work with MT System ver '.$version.'</span>
							
							<input name="mt_export_pack" type="submit" value="Export to pack 2/2" onClick="return confirm(\''.$LANG->getLL('text_export_you_what_export').'\')" />
							<p>
								On your name use special tag: start,social,shop,portal (depending on the version MT System)
							</p>
						';
					}else return $this->show_error_view($LANG->getLL('text_export_error_uidnoroot'));
				}else return $this->show_error_view($LANG->getLL('text_export_error_wronguid'));
				
			}
			function get_export_form($id='')
			{
				global $LANG;
				if($id=='') $info=$LANG->getLL('text_export_id');
				else $info=$LANG->getLL('text_export_id_use');
				
				return $info.'
				<input name="mt_page_uid" type="text" value="'.$id.'" /> <input name="mt_export" type="submit" value="Export this! 1/2" onClick="return confirm(\''.$LANG->getLL('text_export_you_what_export').'\')" />
				';
			}
			function show_error_view($error)
			{
				global $LANG;
				return '<div class="mt_error">'.$error.'</div>';
			}
			function show_error($error)
			{
				global $LANG;
				return '<div class="mt_error">'.$LANG->getLL('text_error_'.$error).'</div>';
			}
			function check_install_set()
			{
				$www_dont=array('http',',');
				$set=array('mtweb_www','mtweb_path','mtweb_pid','installmtweb');
				for($i=0; $i<count($set); $i++)
				{
					if($_POST[$set[$i]]!='') $error=0;
					else
					{
						$error=1;
						break;
					}
					if($set[$i]=='mtweb_www') 
					{
						if(!stristr($_POST[$set[$i]],'.') || stristr($_POST[$set[$i]],$www_dont)) { $error=2; break; }
					}
					if($set[$i]=='mtweb_path')
					{
						$path=$_SERVER['DOCUMENT_ROOT'];
						if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
						$path=$path.'fileadmin/templates/'.$_POST[$set[$i]];
						$get=is_dir($path);
						if($get==1) { $error=3; break; }
					}
					if($_GET['id']!=0) { $error=4; break; }
				}
				return $error;
				
			}
			function get_webtree()
			{
				global $LANG;
				//print_r($_POST);exit;
				//tymczasowo
				$file=array_keys($_POST['installmtweb']);
				$file=$file[0];
				return '
					<div class="mtpage_uid"> 
						<h3>File: '.$file.'</h3>
						<div class="mtrow">
							<label>'.$LANG->getLL('text_what_www').'</label>
							<input name="mtweb_www" type="text" value="'.$_POST['mtweb_www'].'" /><br class="clear" />
						</div>
						
						<div class="mtrow">
							<label>'.$LANG->getLL('text_what_pathname').'</label>
							<input name="mtweb_path" type="text" value="'.$_POST['mtweb_path'].'" /><br class="clear" />
						</div>
						
						<div class="mtrow">
							<label>'.$LANG->getLL('text_what_pid').' </label>
							<input name="mtweb_pid" type="text" value="0" /> <span>recommended uid 0,</span>
							<input name="installmtweb['.$file.']" type="hidden" value="'.$file.'" />
						</div>
						
						<br class="clear" />
					</div>
					<div class="mtsettings"> use friendly links (realUrl)?: <input name="mtweb_realurl" type="checkbox" value="1" /></div>
					<input name="installweb_all" type="submit" value="Install 2/2" />
				';
			}
			function get_mtwebmenager()
			{	
				global $LANG;
				$download='<a href="http://typo3master.pl/zasoby/szablony.html" target="_blank">download more view/template</a>';
				
				
				$path=$_SERVER['DOCUMENT_ROOT'];
				if($path!='/' && substr($path,-1)!='/') $path=$path.'/';
				$path=$path.'fileadmin/mtwebmenager/';
				$get=t3lib_div::getFilesInDir($path,'zip');
				//print_r($path);exit;
				
				$upload='<b><a href="/typo3/sysext/filelist/mod1/file_list.php?id='.rawurlencode($path).'">upload new template from DISC</a></b>';
				
				$start='
				<tr>
					<th>Name</th>
					<th>Option</th>
					<th>Desc</th>
					<th>
					More
					</th>
				</tr>
				';
				
				foreach($get as $file)
				{
					$add[]='
					<tr>
						<td>'.$file.'</td>
						<td><input name="installmtweb['.$file.']" type="submit" value="Install 1/2" /></td>
						<td>none</td>
						<td><a href="/fileadmin/mtwebmenager/'.$file.'">download view/template</a></td>
					</tr>
					';
				}
				if($add[0]=='') $add[]='<tr><td colspan="4">'.$LANG->getLL('text_no_template').'</td></tr>';
				return '<h2>'.$LANG->getLL('text_install_template').'</h2>'.$upload.'<table id="treemtinstall">'.$start.implode("\n",$add).'</table>'.$download;
			}
				
		}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mt_webmenager/mod1/index.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mt_webmenager/mod1/index.php']);
}




// Make instance:
$SOBE = t3lib_div::makeInstance('tx_mtwebmenager_module1');
$SOBE->init();

// Include files?
foreach($SOBE->include_once as $INC_FILE)	include_once($INC_FILE);

$SOBE->main();
$SOBE->printContent();

?>